<template>
    <div class="container">
        <Breadcrumb :items="['menu.list', '维修上报']" />
        <!-- <a-card class="general-card" title="维修上报">
            <a-row>
                <a-col>
                    <a-form :model="formData" label-align="left" auto-label-width>
                        <a-row :gutter="16">
                            <a-col :span="6">
                                <a-form-item field="name" label="终端码">
                                    <a-input v-model="formData.imei" placeholder="请输入" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item field="name" label="设备名称">
                                    <a-input v-model="formData.name" placeholder="请输入" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <div class="search-btn">
                                    <a-button type="primary" style="background: #3E3E69;color: #FFFFFF;"
                                        @click="onPageChange(1)">查询</a-button>
                                    <a-button type="primary" @click="openPage('新增')">新增</a-button>
                                </div>
                            </a-col>
                        </a-row>
                    </a-form>
                </a-col>
            </a-row>
        </a-card>  -->

        <div class="container-table">
            <a-card class="general-card" title="维修上报">
                <a-table :virtual-list-props="{ height: 560 }" :scroll="{ x: '120%', y: '100%' }" :loading="loading"
                    :columns="columns" :data="tableList" :pagination="pagination" @page-change="onPageChange">
                    <template #images="{ record }">
                        <a-image v-if="record.images" width="50" :src="record.images" />
                        <a-image v-else width="50" height="50" src="some-error.png" />
                    </template>
                    <template #repairType="{ record }">
                        {{
                            record.repairType == "student"
                                ? "学生"
                                : record.repairType == "staff"
                                    ? "教职工"
                                    : record.repairType == "worker"
                                        ? "巡检工作人员"
                                        : record.repairType == "guest"
                                            ? "游客"
                                            : "未知"
                        }}
                    </template>
                    <template #status="{ record }">
                        {{ record.status == 'NORMAL' ? '正常' : record.status == 'DAMAGED' ? '维修' : record.status
                            == 'OFFLINE' ? '离线' : '未知' }}
                    </template>
                    <template #operations="{ record }">
                        <div style="display: flex; gap: 10px 0;">
                            <a-popconfirm content="确认是否已维修?" type="warning" @ok="changeData(record)">
                                <a-button type="text" size="small" >
                                    维修
                                </a-button>
                            </a-popconfirm>

                            <a-popconfirm content="确认是否删除?" type="warning" @ok="deleteOneOrder(record.id)">
                                <a-button type="text" status="danger" size="small">
                                    删除
                                </a-button>
                            </a-popconfirm>
                        </div>
                    </template>
                </a-table>
            </a-card>
        </div>


        <a-modal v-model:visible="isShowEdit">
            <template #title>
                {{ isShowEditNaame }}
            </template>
            <div>
                <a-spin class="w-full" :loading="loadingEdit" tip="创建中...">
                    <a-form ref="formRef" :model="form" layout="vertical">
                        <a-form-item :rules="[{ required: true, message: '设备名称必填' }]" field="name" label="设备名称">
                            <a-input v-model="form.name" placeholder="请输入" />
                        </a-form-item>
                        <a-form-item :rules="[{ required: true, message: '终端码必填' }]" field="imei" label="终端码">
                            <a-input v-model="form.imei" placeholder="请输入" />
                        </a-form-item>
                        <a-form-item :rules="[{ required: true, message: '生产厂家必填' }]" field="manufacturer" label="生产厂家">
                            <a-input v-model="form.manufacturer" placeholder="请输入" />
                        </a-form-item>
                        <a-form-item :rules="[{ required: true, message: '当前地址必填' }]" field="location" label="当前地址">
                            <a-input v-model="form.location" placeholder="请输入" />
                        </a-form-item>
                        <!-- <a-form-item :rules="[{ required: true, message: '地址必填' }]" field="address" label="地址">
                            <a-input v-model="form.address" placeholder="请输入" />
                        </a-form-item> -->
                    </a-form>
                </a-spin>
            </div>
            <template #footer>
                <a-button @click="isShowEdit = false">取消</a-button>
                <a-button type="primary" @click="handleOk">提交</a-button>
            </template>
        </a-modal>
    </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue';

import { backfindAll, recordsadd, backdelete, recordsfindid, recordsupdate,repairupdate } from '@/api/hairdryer'




let loading = ref(false);
//查询列表
let formData = ref({
    page: 1,
    size: 10,
})
const pagination = ref({
    current: formData.value.page,
    pageSize: formData.value.size,
    showTotal: true,
    total: 0
}); // 分页属性
const columns = ref([
    {
        title: '设备名称',
        width: '180',
        dataIndex: 'name',
    },
    {
        title: '终端码',
        width: '180',
        dataIndex: 'imei',
    },
    {
        title: '生产厂家',
        width: '150',
        dataIndex: 'manufacturer',
    },
    // {
    //     title: '图片',
    //     width: '150',
    //     dataIndex: 'images',
    //     slotName: 'images',

    // },
    {
        title: '状态',
        width: '150',
        dataIndex: 'status',
        slotName: 'status',

    },
    {
        title: '上报人',
        width: '150',
        dataIndex: 'repairName',
    },
    {
        title: '上报人学号',
        width: '150',
        dataIndex: 'repairAccount',
    },
    {
        title: '上报人电话',
        width: '150',
        dataIndex: 'repairPhone',
    },
    {
        title: '问题描述',
        width: '200',
        dataIndex: 'repairNotes',
    },
    {
        title: '上报人身份',
        width: '150',
        dataIndex: 'repairType',
        slotName: 'repairType',
    },
    {
        title: '创建时间',
        width: '180',
        dataIndex: 'createdAt',
    },
    {
        title: '更新时间',
        width: '180',
        dataIndex: 'updatedAt',
    },
    {
        title: '操作',
        width: '150',
        align: 'center',
        fixed: 'right',
        dataIndex: 'operations',
        slotName: 'operations',
    },
])
const tableList = ref([]);

const onPageChange = (current) => {
    formData.value.page = current;
    pagination.value.current = current;
    getrecordsfindAll()
};

//查询列表
let getrecordsfindAll = async () => {
    loading.value = true;

    try {
        let res = await backfindAll(formData.value)
        console.log(res, 'dfw33');

        tableList.value = res.data.content.map(item => {
            if (item.blowDevice && typeof item.blowDevice === 'object') {
                // 解构 blowDevice，但排除 id、updatedAt、createdAt
                const { id: blowDeviceId, updatedAt: blowDeviceUpdatedAt, createdAt: blowDeviceCreatedAt,images:blowImages, ...restBlowDevice } = item.blowDevice;

                // 合并属性（blowDevice 的剩余属性会展开到外层）
                const flattenedItem = {
                    ...item,          // 保留原有属性（包括外层的 id、updatedAt、createdAt）
                    ...restBlowDevice // 展开 blowDevice 的其他属性
                };

                // 删除原 blowDevice 嵌套对象
                delete flattenedItem.blowDevice;

                return flattenedItem;
            }
            return item;
        });

        console.log(tableList.value);


        pagination.value.total = res.data.totalElements;
        loading.value = false;


    } catch (err) {
        loading.value = false;

    }
}

//新增
let isShowEditNaame = ref('')
let isShowEdit = ref(false);
let loadingEdit = ref(false);
const formRef = ref()
let form = ref({})
//打开新增
const openPage = async (name, data) => {
    isShowEditNaame.value = name
    isShowEdit.value = true;
    form.value = {} //先清空表单
    formRef.value.resetFields() //清空校验



    if (isShowEditNaame.value == '编辑') {
        try {
            let res = await recordsfindid(data.id)
            form.value = res.data
        } catch (error) {

        }
    }
}
//新增编辑确定
const handleOk = async () => {

    form.value.address = form.value.location

    let rs = await formRef.value.validate();
    if (rs) return
    if (isShowEditNaame.value == '新增') {
        setrecordsadd()

    }
    if (isShowEditNaame.value == '编辑') {
        setquick_durationsupdate()
    }


}
//新增设备
const setrecordsadd = async () => {
    loadingEdit.value = true
    try {
        let res = await recordsadd(form.value)
        Message.success('新增成功')
        loadingEdit.value = false
        getrecordsfindAll() //获取列表
        isShowEdit.value = false
    } catch (error) {
        loadingEdit.value = false
        Message.error('新增失败！')
    }
}

//编辑规则
const setquick_durationsupdate = async () => {
    try {
        let res = await recordsupdate(form.value.id, form.value)
        Message.success('编辑成功')
        loadingEdit.value = false
        getrecordsfindAll() //获取列表
        isShowEdit.value = false
    } catch (error) {
        loadingEdit.value = false
        Message.error('编辑失败！')

    }
}


//删除设备
const deleteOneOrder = async (id) => {
    try {
        let res = await backdelete(id, {})
        Message.success('删除成功')
        getrecordsfindAll() //获取列表
    } catch (error) {
        Message.error('删除失败！')

    }
}

//修改设备
const changeData = async (data)=>{
    let myData = {...data}
    myData.status = 'NORMAL'
   try {
        let res = await repairupdate(myData.id, myData)
        Message.success('修改成功')
        getrecordsfindAll() //获取列表
    } catch (error) {
        Message.error('修改失败！')

    }
}

onMounted(() => {
    getrecordsfindAll()
})

</script>
<style scoped lang="less">
.container {
    padding: 0 20px 20px 20px;

    .search-btn {
        width: 100%;
        display: flex;
        justify-content: flex-end;
        gap: 0 10px;
    }


    .container-table {
        margin-top: 20px;

        .general-card {
            box-sizing: border-box;
            padding: 20px 0;
        }
    }
}
</style>